package xju_3_4.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;


@Configuration
@ComponentScan(basePackages = "xju_3_4")
@PropertySource("classpath:jdbc.properties")
@EnableTransactionManagement // 开启申明事务
public class JavaConfig {

    @Value("${driver}")
    private String driver;
    @Value("${url}")
    private String url;
    @Value("${username}")
    private String username;
    @Value("${password}")
    private String password;


    // 配置数据源
    @Bean
    public DruidDataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername("root");
        dataSource.setPassword(password);
        System.out.println(driver);
        System.out.println(url);
        System.out.println(username);
        System.out.println(password);
        return dataSource;
    }

    // 配置jdbc模板
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    // 配置事务管理器
    @Bean
    public TransactionManager  transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
